const { userRecommend } = require("../../utils/request");
const config = require("../../utils/config");

Page({
  data: {
    artworks: [],  // 艺术作品列表数据
    leftColumn: [],   // 艺术作品列表左边数据
    rightColumn: [],   // 艺术作品列表右边数据
    pageNum: 1, // 当前页数
    pageSize: 10, // 每页显示的条数
    isLoading: false, // 是否正在加载数据
    hasMore: true, // 是否还有更多数据
  },

  onLoad() {
    this.loadArtworks();
  },

  onReachBottom() {
    // 当页面滚动到底部时触发
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadMoreArtworks();
    }
  },

  async loadArtworks() {
    this.setData({ isLoading: true });
    const { pageNum, pageSize } = this.data;

    userRecommend({ pageNum, pageSize }).then(res => {
      if (res.code === '00000' && res.data && res.data.list) {
        // this.processArtworks(res.data.list);
        const updatedArtworks = res.data.list.map((artwork) => ({
          ...artwork,
          primaryImageSmallUrl: `${config.ImageURL}${artwork.primaryImageSmallUrl}`,
        }));
        // this.setData({ artworks: [...this.data.artworks, ...updatedArtworks] });
        this.setData({ 
          artworks: [...this.data.artworks, ...updatedArtworks],
          hasMore: updatedArtworks.length >= this.data.pageSize
         });
        // this.setData({ hasMore: res.data.list.length >= pageSize });
      } else {
        wx.showToast({
          title: 'Loading failed, please try again',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.showToast({
        title: 'Network error, please retry',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({ isLoading: false });
    });
  },

  async loadMoreArtworks() {
    const { pageNum } = this.data;
    this.setData({ pageNum: pageNum + 1 });
    this.loadArtworks();
  },

  async processArtworks(artworks) {
    const updatedArtworks = artworks.map((artwork) => {
      const imageUrl = `${config.ImageURL}${artwork.primaryImageSmallUrl}`;
      return {
        ...artwork,
        primaryImageSmallUrl: imageUrl, // 更新 primaryImageSmallUrl 属性
      };
    });

    const { leftColumn, rightColumn } = this.data; // 获取当前列

    // 简单交替分配到两列
    updatedArtworks.forEach((artwork, index) => {
      if (index % 2 === 0) {
        leftColumn.push(artwork);
      } else {
        rightColumn.push(artwork);
      }
    });

    // 更新列数据
    this.setData({ leftColumn, rightColumn });
  },
});
